#include "app.h"


// #######################################################################################################
// JOYSTICK
// Quando o teclado permanecer pressionado o valor das teclas serão registrados para serem lidos.
// 	Nunca será registrador valor 0 na varredura
// A função de leitura vai retornar com o valor registrado pela varredura, ou o valor 0 caso na varredura
//		não foi registrado nada
// #######################################################################################################
static volatile int joy;
void joy_Init(void) {
	joy = 0;
}

// retonra com o valor da tecla pressionada.
int joy_Read(void) {
	int j = joy; // retorna com o valor da tecla pressionada
	joy = 0; // sinaliza que não tem mais tecla sendo pressionada
	return j;
}

void joy_Tick(void) {
	// LEITURA DO JOYSTICK a cada 16ms
	static volatile uint timeRead = 0;
	if (timeRead) timeRead--;
	if (timeRead == 0) {
		timeRead = 16;
		// ssp1_Init(SSP0_MASTER, SSP0_CPOL_H|SSP0_CPHA_H|SSP0_DSS_8); // inicar o barramento SPI a 400Khz
		int buttons;
		joy_ReadControls(&buttons);
		// ssp1_Init(SSP0_MASTER, SSP0_STANDARD); // inicar o barramento SPI a 400Khz
		if (buttons > 0) joy = buttons;
	}
}

// #######################################################################################################
// KEYBOARD
// #######################################################################################################
void onKeyDown(char key) {
	lprintf("onKeyDown key [0x%x]"CMD_TERMINATOR, key);
	if (key == SW0) beep_Play(4);
	else if (key == SW1) beep_Play(5);
	else if (key == SW2) beep_Play(6);
}

void onKeyPress(char key __attribute__ ((unused)) ) {
	lprintf("onKeyPress key [0x%x] fastInc[%d] "CMD_TERMINATOR, key, gkey_FastInc);
}

void onKeyUp(char key __attribute__ ((unused)) ) {
	lprintf("onKeyUp key [0x%x] fastInc[%d] "CMD_TERMINATOR, key, gkey_FastInc);
}

// #######################################################################################################
// RELAYS
// #######################################################################################################
void relay_Init(void) {
	relay1_Init();
	relay2_Init();

	control.relay1.st = 0;
	control.relay1.timeout = 0;

	control.relay2.st = 0;
	control.relay2.timeout = 0;
}

// Liga ou desliga o rele
//	parametro rly: sinaliza qual o rele vamos acessar. valor 0 ou 1
//	parametro st: pdON liga o rele e pdOFF desliga o rele;
//	parametro timeout: O tempo em segundos que o rele vai ficar no estado atual e voltar para o estado inverso
//		Se colocar valor 0, permanece no estado atual até o próximo comando
int relay_Set(int rly, int st, uint timeout) {
	pRelay rl;

	if ( (rly < 0) || (rly > 1) ) return errDEVICE_NOT_FOUND;
	if (rly == 0) rl = &control.relay1; else rl = &control.relay2;

	rl->timeout = timeout*1000;
	rl->st = st;

	return pdPASS;
}

void relay_Tick(void) {
	if (control.relay1.st) relay1_On(); else relay1_Off();
	if (control.relay2.st) relay2_On(); else relay2_Off();
	if (control.relay1.timeout > 0) control.relay1.timeout--;
	if (control.relay2.timeout > 0) control.relay2.timeout--;
	//colocar depois do acionamento para que seja certinho a contagem dos tempos
	if (control.relay1.timeout == 1) control.relay1.st ^= 1;
	if (control.relay2.timeout == 1) control.relay2.st ^= 1;
}

// #######################################################################################################
// APPLICATION
// #######################################################################################################
void app_Init(void) {
	control.ticks = 0;
	control.key = 0;

	relay_Init();
}

// Aqui descre, ou chame, códigos que controlam tempos ou que sejam executados em tempos reguladores
void app_Tick(void) {
	// ATENÇÃO:  tempo de execução de TODOS os TICKS dentro dessa função NÃO pode ser superior a 1ms
	ledError_Tick();
	beep_Tick();
	gKey_Tick();
	relay_Tick();
	joy_Tick();

	// LEITURA DO TECLADO a cada 3ms
	static volatile uint timeReadKey = 0;
	static int bufKey[3];
	static uint idx = 0;
	if (timeReadKey) timeReadKey--;
	if (timeReadKey == 0) {
		timeReadKey = 3;

		// fazer debounce no teclado
		bufKey[idx%3] = (sw0_PIN&sw0_NUMPIN)?SW0:0;
		bufKey[idx%3] |= (sw1_PIN&sw1_NUMPIN)?SW1:0;
		bufKey[idx%3] |= (sw2_PIN&sw2_NUMPIN)?SW2:0;

		if ( (bufKey[0] == bufKey[1]) && (bufKey[1] == bufKey[2]) ) {
			control.key = bufKey[2]&0x7; // para que não pegar o botão de reconfigure
		}
		if (idx == 2) idx = 0; else idx++;
	}

	control.ticks++; // Contador de ticks do sistema
}


// Aqui descre, ou chame, códigos que não controlam tempos ou que não sejam executados em tempo reguladores, pelo menos diretamente
void app_Process(void) {
	int buttons = joy_Read();
	switch (buttons) {
	case joypsKEY_UP: beep_Play(4); break;
	case joypsKEY_DOWN: beep_Play(5); break;
	case joypsKEY_LEFT: beep_Play(6); break;
	case joypsKEY_RIGHT: beep_Play(1); break;
	case joypsKEY_CIRCLE: beep_Play(0); break;
	}


//	static uint ticks_d = 0;
//	if ( (control.ticks%50==0) && (control.ticks != ticks_d) ) {
//		ticks_d = control.ticks;
//	}
}

